package com.factory.code.controller;


import com.factory.code.controller.param.ConnectionParam;
import com.factory.code.controller.param.TableNameParam;
import com.factory.code.controller.vo.R;
import com.factory.code.lib.database.model.DatebaseTypeAndDriverModel;
import com.factory.code.lib.database.model.TableColumnModel;
import com.factory.code.lib.database.model.TableInfoModel;
import com.factory.code.service.DatabaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("database")
@Api(tags = "数据库管理")
public class DatabaseController {

    @Autowired
    private DatabaseService databaseService;

    @ApiOperation(value = "测试连接", notes = "测试连接是否可用")
    @PostMapping("/testConnection")
    public R<Object> testConnection(@RequestBody ConnectionParam param) {
        try {
            databaseService.testConnection(param);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.OK;
    }

    @ApiOperation(value = "根据项目id查询所有表名")
    @PostMapping("listTableName/{projectId}")
    public R<List<String>> listTableName(@PathVariable("projectId") Integer projectId) {
        return R.ok(databaseService.listTableName(projectId));
    }

    @ApiOperation(value = "根据项目id查询所有表信息")
    @PostMapping("getTableAll/{projectId}")
    public R<List<TableInfoModel>> getTableAll(@PathVariable("projectId") Integer projectId) {
        return R.ok(databaseService.getTableAll(projectId));
    }

    @ApiOperation(value = "查询指定表列表信息")
    @PostMapping("listFieldModel")
    public R<List<TableColumnModel>> listFieldModel(@RequestBody TableNameParam param) {
        return R.ok(databaseService.listFieldModel(param));
    }

    @ApiOperation(value = "获取可用的 数据库类型和数据库驱动")
    @PostMapping("listValidDbType")
    public R<List<DatebaseTypeAndDriverModel>> listValidDbType() {
        return R.ok(databaseService.listValidDbType());
    }

}
